function Se() {
    var S = this;
    this.default = {
        timeout: 15000,
        sid: '00000000000000000000000000000000',
        isLogin: false
    };
    this.id = 0;
    this.option = {};

    this.getId = function(){
        return this.id++;
    };


    this._call = function(req, cb) {
        return $.ajax('/ubus', {
            cache:       false,
            contentType: 'application/json',
            data:        JSON.stringify(req),
            dataType:    'json',
            type:        'POST',
            timeout:     S.default.timeout,
            _rpc_req:   req
        }).then(cb, cb);
    };

    this.checkLogin = function(){
        var sid = S.cookieUtil.get('sid');
        if(sid)
            S.option.isLogin = true;
        return sid;
    };

    this.init  = function() {
        this.option = this.default;
        var sids = S.checkLogin();
        if (!sids || sids == undefined || sids == "undefined" || sids == "") {
            this.onReadre.login();
            this.layout.bar();
            this.layout.show();
        }
        else {
            //alert("错误11111");
            this._init();
        }
    }


    this.tools = {
        heredoc : function(fn){
            return fn.toString().replace(/\/\*/,'').replace(/\*\//,'').split('\n').slice(1,-1).join('\n') + '\n';
        },
        stopPropagation : function(event){
            if (event.stopPropagation) {
                event.stopPropagation();
            }else if (window.event) {
                window.event.cancelBubble = true;
            }
        },
        setCookie:function(name,valueg,time){
            var exp = new Date();
            exp.setTime(exp.getTime() + time);
            S.cookieUtil.set(name,valueg,exp.toGMTString());
        }
    };


    this.layout = {
        show:function(){
            if(typeof S.option.configs == "undefined" || typeof S.option.configs == undefined )S.option.configs = {};
            var str = S.tools.heredoc(function(){
                /*
                 <div class="con">
                 <h3>设备状态：</h3>
                 <div class="con_li"><span>设备名称：</span><b id="rotu_name"></b></div>
                 <div class="con_li"><span>LAN口IP：</span><b id="lan_ip"></b></div>
                 <div class="con_li"><span>WAN口MAC：</span><b id="mac"></b></div>
                 <div class="con_li"><span>WIFI类型：</span><b id="wifi_status"></b></div>

                 <div class="con_li"><span>WIFI名称：</span><b id="ssid"></b></div>
                 <div class="con_li"><span>WIFI密码：</span><b id="wifi_passwd"></b></div>
                 <div class="con_li"><span>配对设备ID：</span><b id="hulian_id"></b></div>
                 <div class="con_li"><span>互连状态：</span><b id="hlzts"></b></div>

                 </div>
                 <div class="con">
                 <h3>Wan口状态：</h3>
                 <div class="con_li">
                 <span>WAN口接入类型：</span><b id="wan_state"></b>
                 </div>
                 <div id="wan_state_waninfos">
                 </div>
                 <!--<div class="con_li">
                 <span>WWAN DHCP状态：</span><b id="wwan_dhcp_state"></b>
                 </div>-->
                 <div id="wwan_state_wwaninfos">
                 </div>
                 <div class="con_li_b"><button id="flash"><a href="javascript:;">刷新</a></button></div>
                 */
            });

            $('#content').html(str);
            S.onReadre.init();
            $("#flash").click(function () {
                location.reload(true);
            });
        },
        bar:function(){
            var str = S.tools.heredoc(function(){
                /*
                 <div class="top">
                 <img src="resource/img/logo.png">
                 <span>模块设置</span>
                 <b id="timess"></b>
                 </div>
                 <div  class="left">
                 <ul id="bars">
                 <li no="0" class="dq"><a href="javascript:;">当前状态</a></li>
                 <li no="1"><a href="javascript:;">网络设置</a></li>
                 <li no="2"><a href="javascript:;">无线设置</a></li>
                 <li no="3"><a href="javascript:;">互连设置</a></li>
                 <li no="4"><a href="javascript:;">密码修改</a></li>
                 <li no="5"><a href="javascript:;">退出</a></li>
                 </ul>
                 </div>
                 <div id="content" class="content">
                 </div>
                 */
            });
            $('body').html(str);
           // S.onReadre.bar();
        }

    };


    this.onClall = {
        _doGetUser:function(data){
            if(data){
                S.option.configs.username = data.result[1].value;
            }
        },
        _dogGetLan:function(data){
            if(typeof data.result != undefined && typeof data.result != "undefined"){
                S.option.configs.lan = data.result[1].values;
                if(S.onReadre.index == 0){
                    $("#lan_ip").html(S.option.configs.lan.ipaddr);
                }
            }
        },
        _doGetWifiSta:function(data){
            if(data){
                S.option.configs.wifi_iface = data.result[1].values;
                S.option.configs.wifi_iface.disabled = S.option.configs.disabled = data.result[1].values.disabled == undefined || data.result[1].values.disabled == 0 || data.result[1].values.disabled == "0" ? 0 : 1;
                S.option.configs.encryption = data.result[1].values.encryption;
                S.option.configs.ssid = data.result[1].values.ssid;
                if(S.onReadre.index == 0){
                    $("#ssid").html(S.option.configs.ssid);
                    $("#wifi_passwd").html(S.option.configs.wifi_iface.key);
                    if(S.option.configs.wifi_iface.disabled == 0){
                        if(S.option.configs.wifi_iface.mode == 'sta'){
                            $("#wifi_status").html('客户端(client)');}else{$("#wifi_status").html('无线访问点(AP)');}
                    }else{
                        $("#wifi_status").html('关闭');

                    }
                }
            }
        },
        _doGetHostName:function(data){
            if(data){
                S.option.configs.hostname = data.result[1].value;
                if(S.onReadre.index == 0){
                    $("#rotu_name").html(S.option.configs.hostname);
                }
            }
        },
        _doCommitNetwork:function(){
            S.getId();
            var reg =
            {
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'uci','commit',{config:'network'}]
            };
            S._call(reg,function(data){
                var lists = [
                    S.onReadre.list.WlanStatus
                ];
                S.onReadre.get(lists);
            });
        },
        _doCommitHulian:function(){
            S.getId();
            var reg =
            {
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'uci','commit',{config:'routedif'}]
            };
            S._call(reg,function(data){
                var lists = [
                    //  S.onReadre.list.serial
                ];
                S.onReadre.get(lists);
            });
        }
    };

    this.onReadre = {
        index:0,
        sid:null,
        list:{
            reboot:{
                params:['0','luci2.system','reboot','{}']
            },
            restart:{
                params:['0','luci2.system','init_action',{name:"",action:""}]
            },
            //user:{
            //    params:['0','uci','get',{config:'rpcd',section:'@login[0]',option:'username'}],
            //    callback: S.onClall._doGetUser
            //},
            lan:{
                params:['0','uci','get',{config:'network',section:'lan'}],
                callback: S.onClall._dogGetLan
            }
            //setStaNetworkwwan:{
            //    params:['0','uci','add',{config:'network',type:'interface',values:{'proto':'dhcp'}}],
            //    callback: S.onClall._doCommitNetwork
            //},
            //setStaNetwork:{
            //    params:['0','uci','set',{config:'network',section:''}],
            //    callback: S.onClall._doCommitNetwork
            //},
            //delStaWifiOption:{
            //    params:['0','uci','delete',{config:'wireless',section:'@wifi-iface[0]'}],
            //    callback: S.onClall._doCommitWireless
            //},
            //wifi:{
            //    params:['0','uci','get',{config:'wireless',section:'@wifi-iface[0]'}],
            //    callback: S.onClall._doGetWifiSta
            //},
            //bit:{
            //    params:['0','uci','get',{config:'bit',section:'@bit[0]'}],
            //    callback: S.onClall._doGetBit
            //},
            //commit_wan_dhcp:{
            //    params:['0','uci','set',{config:'network',section:'wan'}],
            //    callback: S.onClall._doCommitNetwork
            //},
            //setWifiConfig:{
            //    params:['0','uci','set',{config:'wireless',section:'@wifi-iface[0]'}],
            //    callback: S.onClall._doCommitWireless
            //},
            //hulian:{
            //    params:['0','uci','set',{config:'routedif',section:'@routedif[0]'}],
            //    callback: S.onClall._doCommitHulian
            //},
            //delte_network_option:{
            //    params:['0','uci','delete',{config:'network',section:'wan'}]
            //}
        },
        bar:function(){
            //   S.isLogout();
            var obj = $("#bars li");
            var base = this;
            //当前状态
            obj.eq(0).click(function(){
                //  S.isLogout();
                if(base.index == 0) return;
                S.layout.show();
                S.onReadre.focusbg();
                $(this).addClass('dq');
                base.index = 0;
            });
            //网络设置
            obj.eq(1).click(function(){
                S.isLogout();
                if(base.index ==1) return;
                //   S.layout.setting();
                S.onReadre.focusbg();
                $(this).addClass('dq');
                base.index = 1;
            });
            //无线设置
            obj.eq(2).click(function(){
                S.isLogout();
                if(base.index ==2) return;
                S.onReadre.focusbg();
                // S.layout.wifiSet();
                base.index = 2;
                $(this).addClass('dq');
            });
            //互联设置
            obj.eq(3).click(function(){
                S.isLogout();
                if(base.index ==3) return;
                S.onReadre.focusbg();
                S.layout.hulian();
                base.index = 3;
                $(this).addClass('dq');
            });
            //系统设置
            obj.eq(4).click(function(){
                S.isLogout();
                if(base.index ==4) return;
                S.layout.setpass();
                S.onReadre.focusbg();
                $(this).addClass('dq');
                base.index = 4;
            });
            //退出
            obj.eq(5).click(function(){
                S.isLogout();
                S.onReadre.logout();
                S.onReadre.focusbg();
                $(this).addClass('dq');
            });
        },
        reboot:function(){
            S.getId();
            var reg ={
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'luci2.system','reboot',{}]
            };
            S._call(reg,function(data){
            });
        },
        focusbg:function(){
            $("#bars li").removeClass('dq');
        },
        logout:function(){
            S.start = true;
            var reg ={
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[S.option.sid,'session','destroy',{session: S.option.sid}]
            };
            S._call(reg,function(data){});
            S.option = {};
            S.cookieUtil.unset('sid');
            location.reload(true);
        },
        login:function(){

            S.getId();

            //var name = $('#username').val();
            //var pa = $("#passm").val();
            var name = "admin";
            var pa = "admin";
            var reg ={
                id: S.id,
                jsonrpc:'2.0',
                method:"call",
                params:[ '00000000000000000000000000000000','session','login',{username:name,password:pa}]
            };
            $.ajax('/ubus', {
                cache:       false,
                contentType: 'application/json',
                data:        JSON.stringify(reg),
                dataType:    'json',
                type:        'POST',
                timeout:     S.default.timeout,
                _rpc_req:   reg,
                error:function(){
                    alert("登录失败");
                },
                async:false,
                success:function(data){
                    if(data){
                        if(typeof data.result != undefined && typeof data.result != "undefined"){
                            if(data.result[0] == 0){
                                S.tools.setCookie('isLogin', 1);
                                var returndata = data.result[1];
                                S.option.sid = returndata.ubus_rpc_session;
                                S.option.isLogin = true;
                                S.tools.setCookie('sid',returndata.ubus_rpc_session,S.option.timeout);
                                alert("登陆成功");
                                //S.layout.bar();
                                //S.layout.show();
                            }else{
                                S.onReadre.logout();
                                alert("登录失败1");
                            }
                        }else{
                            S.onReadre.logout();
                            alert("登录失败2");

                        }
                    }else{
                        S.onReadre.logout();
                        alert("登录失败3");
                    }
                }
            });
        },
        get:function(list){
            if(list.length>0){
                var regs =[];
                for(var ii=0;ii<list.length;ii++){
                    S.getId();
                    alert(S.option.sid);
                    alert(S.id);
                    if(list[ii].params[0] == '0') list[ii].params[0] = S.option.sid;
                    regs.push({
                        id: S.id,
                        jsonrpc:'2.0',
                        method:"call",
                        params:list[ii].params
                    });
                }
                S._call(regs,function(data){
                    alert("准备进call");
                    if(data){
                        for(var i=0;i<data.length;i++){
                            if(typeof (list[i].callback) != "undefined" && list[i].callback != undefined){
                                list[i].callback(data[i]);
                            }
                        }
                    }
                });
            }
        },
        set:function(list){
            if(list.length>0){
                var regs =[];
                for(var ii=0;ii<list.length;ii++){
                    S.getId();
                    if(list[ii].params[0] == '0') list[ii].params[0] = S.option.sid;
                    regs.push({
                        id: S.id,
                        jsonrpc:'2.0',
                        method:"call",
                        params:list[ii].params
                    });
                }
                S._call(regs,function(data){
                    if(data){
                        for(var i=0;i<data.length;i++){
                            if(typeof (list[i].callback) != "undefined" && list[i].callback != undefined){
                                list[i].callback(data[i]);
                            }
                        }
                    }
                });
            }
        },
        init:function(){
            this.sid = S.option.sid;
            var lists = [
                //this.list.user,
                this.list.lan,
                //this.list.wifi,
                //this.list.bit,
            ];
            this.get(lists);
        },
        setpm:function(){
            S.isLogout();
            var spd = $.trim($("#spd").val());
            var rspd = $.trim($("#rspd").val());
            if(spd !="" && spd.length >0){
                if(spd.length<8){
                    alert("密码必须大于8位");
                    return;
                }
                if(spd != rspd){
                    alert("密码错误");
                    return;
                }
                var reg ={
                    id: S.id,
                    jsonrpc:'2.0',
                    method:"call",
                    params:[S.option.sid,'luci2.system','password_set',{user: S.option.configs.username,password:spd}]
                };
                S._call(reg,function(data){
                    S.onReadre.logout();
                });
            }else{
                alert("密码错误");
                return;
            }
        },
        setHulian:function(){
            S.isLogout();
            var id = $('#hulian_id').val();
            var pass =  $('#hulian_pass').val();
            var mtus = $('#hulian_mtu').val();
            var lists = [];
            var params = {};
            var params = this.list.hulian;
            params.params[3].values = {};
            params.params[3].values = {"remoteid":id,"remotepass":pass,"mtu":mtus};
            lists[0] = params;
            S.onReadre.set(lists);
        }
    };

    this.regEvent =  {
        doLoginCheck:function(){
            $("#loginButton").click(function(event){
                //  S.tools.stopPropagation(event);
                S.onReadre.login();
            });
        },
        doHulian:function(){
            $('#hulian_button').click(function(){
                S.isLogout();
                S.onReadre.setHulian();
                S.onReadre.reboot();
            });
        }
    };

    this.cookieUtil = {
        get:function(name){
            var cookieName = encodeURIComponent(name) + "=" ,
                cookieStart = document.cookie.indexOf(cookieName),
                cookieValue = null;
            if(cookieStart > -1){
                var cookieEnd = document.cookie.indexOf(";",cookieStart);
                if(cookieEnd == -1){
                    cookieEnd = document.cookie.length;
                }
                cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
            }
            return cookieValue;
        },
        set:function(name, value, expires, path, domain, secure){
            var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);
            if(expires instanceof Date){
                cookieText += ";expires=" + expires.toGMTString();
            }
            if(path){
                cookieText += ";path=" + path;
            }
            if(domain){
                cookieText += ";domain=" + domain;
            }
            if(path){
                cookieText += ";secure=" + secure;
            }
            document.cookie = cookieText;
        },
        unset:function(name, path, domain, secure){
            this.set(name, "" , new Date(0), path, domain, secure);
        },
        checkCookie:function(name){
            var name=get(name);
            if (name!=null && name!=""){
                return name;
            }else{
                return false;
            }
        }
    };

}
